#include "stdafx.h"
#include "TicketInfoWindow.h"

#include "../MyUtils/StringUtils.h"
#include "TrainTicketModule.h"

#include <ShellAPI.h>


TicketInfoWindow::TicketInfoWindow()
{
}

TicketInfoWindow::~TicketInfoWindow()
{
}

CDuiString TicketInfoWindow::GetSkinFile()
{
	return _T("ticket_info_skin.xml");
}

LPCTSTR TicketInfoWindow::GetWindowClassName()const
{
	return _T("TicketInfoWindow");
}

void TicketInfoWindow::SetTrainTicketModule(ITrainTicketModule* pModule)
{
	m_pTrainTicketModule = pModule;
}

void TicketInfoWindow::InitWindow()
{
	CButtonUI* pBtnClose = (CButtonUI*)m_pm.FindControl(_T("btn_close"));
	if (pBtnClose)
	{
		pBtnClose->signal_onClicked.connect(this, &TicketInfoWindow::OnCloseWindow);
	}
}

void TicketInfoWindow::OnFinalMessage(HWND hWnd)
{
	WindowImplBase::OnFinalMessage(hWnd);

	delete this;
}

void TicketInfoWindow::OnCloseWindow(CControlUI* pbtn)
{
	Close();
}

void TicketInfoWindow::ShowInfo(HWND hWnd, const TrainTicketInfo& info)
{
	Create(hWnd, _T("TicketInfo"), UI_WNDSTYLE_FRAME, 0L, 0, 0, 600, 400);
	CenterWindow();


	CControlUI* pInfoTime = m_pm.FindControl(_T("lbl_tain_ticket_time"));
	if (pInfoTime)
	{
		pInfoTime->SetText(info.dataTime.c_str());
	}

	CControlUI* pInfoTrainNo = m_pm.FindControl(_T("lbl_tain_ticket_no"));
	if (pInfoTrainNo)
	{
		pInfoTrainNo->SetText(info.trainNumber.c_str());
	}

	CControlUI* pInfDest = m_pm.FindControl(_T("lbl_tain_ticket_dest"));
	if (pInfDest)
	{
		pInfDest->SetText(info.destination.c_str());
	}

	CControlUI* pInfoPrice = m_pm.FindControl(_T("lbl_tain_ticket_price"));
	if (pInfoPrice)
	{
		CDuiString strPrice; strPrice.Format(_T("%.1f"), info.price);
		pInfoPrice->SetText(strPrice.GetData());
	}

	CControlUI* pInfoMinutes = m_pm.FindControl(_T("lbl_tain_ticket_minutes"));
	if (pInfoMinutes)
	{
		CDuiString strTime;
		strTime.Format(_T("%d:%d"), info.minutes / 60, info.minutes % 60);

		pInfoMinutes->SetText(strTime.GetData());
	}

	CButtonUI* pBtnBuy = (CButtonUI*)m_pm.FindControl(_T("btn_tain_ticket_buy"));
	if (pBtnBuy)
	{
		CDuiString sTicketNum; sTicketNum.Format(_T("%ld"), info.ticketNumber);
		pBtnBuy->AddCustomAttribute(_T("ticket_num"), sTicketNum.GetData());
		pBtnBuy->signal_onClicked.connect(this, &TicketInfoWindow::OnBuyTicket);
	}

	ShowModal();
}

void TicketInfoWindow::OnBuyTicket(CControlUI* pbtn)
{
	if (!pbtn || !m_pTrainTicketModule)
	{
		return;
	}

	std::TString sTicketNum = pbtn->GetCustomAttribute(_T("ticket_num"));
	ULong ticketNum = Utils::StringUtils::TStringToULong(sTicketNum);
	const TrainTicketInfo* pTicket = m_pTrainTicketModule->GetTicketInfo(ticketNum);
	if (!pTicket)
	{
		return;
	}

	bool sucess = m_pTrainTicketModule->BuyTicket(pTicket->ticketNumber);
	if (sucess)
	{
		MessageBox(GetHWND(), _T("Buy Successed!"), _T("Tips"), MB_OK);
	}
	else
	{
		MessageBox(GetHWND(), _T("Buy Failed!"), _T("Tips"), MB_OK);
	}

	Close();
}